//
//  WBRefreshControl.swift
//  WeChat
//
//  Created by 梁迪 on 15/12/22.
//  Copyright © 2015年 梁迪. All rights reserved.
//

import UIKit
import SnapKit

private let RefreshViewHeight:CGFloat = 60

enum WBRefreshStatue:Int{
    
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
    
    
}

class WBRefreshControl: UIControl {
    
    
    //定义属性保存上一次的状态
    var oldStatue:WBRefreshStatue = .Normal
    //定义外部模型属性
    var statue: WBRefreshStatue = .Normal{
        didSet{
            switch statue{
            case .Pulling:
                print("准备起飞")
                tipLabel.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                print("正在起飞")
                 tipLabel.text = "正在起飞"
                arrowIcon.hidden = true
               loadIcon.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top += RefreshViewHeight
                    self.scrollView?.contentInset = inset
                    
                })
                
                
                sendActionsForControlEvents(.ValueChanged)
                
                case .Normal:
                print("下拉起飞")
                 tipLabel.text = "下拉起飞"
                arrowIcon.hidden = false
                loadIcon.stopAnimating()
                
              
                
                if oldValue == .Refreshing{
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top -= RefreshViewHeight
                        self.scrollView?.contentInset = inset
                        
                    })
                    
                    
                }
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
                
            }
            
            oldStatue = statue
        }
  }
    
    //实现 KVO
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //获取tableView的临界值
        let insetTop = scrollView?.contentInset.top ?? 0
        let condationValue = -(RefreshViewHeight + insetTop)
        
        let offsetY = scrollView?.contentOffset.y ?? 0
        
        
        print("con-----||\(condationValue)")
        print("off-------||\(offsetY)")
        
        
        if scrollView!.dragging{
            if statue == .Normal && offsetY < condationValue{
                statue = .Pulling
                
            }else if statue == .Pulling && offsetY > condationValue{
                
               statue = .Normal
                
            }
            
        
        }else{
            
            if statue == .Pulling{
                
                statue = .Refreshing
            }
            
            
            
        }
        
    
        
    }
    
    func endRefreshing(){
        
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_SEC))
        
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
            
        }
        
        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let myFather = newSuperview as? UIScrollView{
            
            self.scrollView = myFather
            
            
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
            
        }
        
        
        
    }
    
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
        
    }
    
// 定义属性 记录父视图
    var scrollView:UIScrollView?
    
    override init(frame: CGRect) {
        
        //在视图内部定制frame
        let  rect = CGRect(x: 0, y: -RefreshViewHeight, width: screenW, height: RefreshViewHeight)
    
        super.init(frame: rect)
        
        setupUI()
        backgroundColor = UIColor.randomColor()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        addSubview(arrowIcon)
        addSubview(tipLabel)
        addSubview(loadIcon)
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
            
            
        }
        
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(-5)
            make.centerY.equalTo(tipLabel.snp_centerY)
            
        }
        
        loadIcon.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
    }
    
    
    //懒加载所有的子视图
    private lazy var arrowIcon:UIImageView = UIImageView(image: UIImage(named: "timeline_icon_retweet"))
    
    private lazy var tipLabel:UILabel = UILabel(title: "下拉起飞", color: UIColor.randomColor(), fontSize: 14)
    private lazy var loadIcon :UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
    

}
